import BabelCore, {PluginObj} from "@babel/core";
import {NodePath} from "@babel/traverse";
import {CallExpression} from "@babel/types";
import * as path from "path";

let projectBasePath = process.cwd() + path.sep

function getFilePath(filePath: string): string {
  filePath = filePath.replace(projectBasePath, '')
  filePath = filePath.split('?')[0]
  return filePath
}

export default function (babel: typeof BabelCore): PluginObj {
  let t = babel.types
  return {
    name: "babel-plugin-getFilePath",
    visitor: {
      CallExpression(path: NodePath<CallExpression>, state) {
        let node = path.node
        let callee = node.callee;
        if (callee.type === 'MemberExpression') {
          const property = callee.property;
          if (property.type === 'Identifier') {
            const name1 = property.name;
            if (name1 === '__getFilePath__') {
              // 这里就找到了 window.__getFilePath__
              path.replaceWith(t.stringLiteral(getFilePath(state.filename)))
            }
          }
        } else if (callee.type === 'Identifier') {
          if (callee.name === '__getFilePath__') {
            // 找到 __getFilePath__
            path.replaceWith(t.stringLiteral(getFilePath(state.filename)))
          }
        }
      },
    },
  };
}
